package cn.jinjimi.app.main.adapter;

import android.content.Context;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.DateUtils;
import cn.jinjimi.base.util.ViewUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.entity.Article;
import cn.jinjimi.app.entity.Attachment;
import cn.jinjimi.app.entity.Category;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.store.entity.ArticleEntity;
import cn.jinjimi.app.main.adapter.extend.MyBaseAdapter;
import cn.jinjimi.app.main.widget.MatchTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tony on 11/24/14.
 * modify by Roy on 15-10-23
 */
public class ArticleAdapter extends MyBaseAdapter<Article> {

    private LayoutInflater layoutInflater;
    private Category category;
    private Context mContext;
    private String matchText;

    public ArticleAdapter(Context context) {
        this.mContext = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    public void setCategory(Category category) {
        this.category = category;
        notifyDataSetChanged();
    }

    public void setMatchText(String matchText) {
        this.matchText = matchText;
    }

    public String getMatchText() {
        return matchText;
    }

    public void syncLocalData(List<Article> articleList) {
        setItems(mixLocalData(articleList));
    }

    public void addAll(List<Article> articles) {
        addItems(mixLocalData(articles));
    }

    /**
     * 检索所有已读文章, 并标记状态
     *
     * @param articleList
     */
    private List<Article> mixLocalData(List<Article> articleList) {
        if (articleList == null)
            return null;
        List<String> ids = new ArrayList<String>();
        for (Article article : articleList) {
            ids.add(article.getId());
        }

        if (ids.size() == 0)
            return articleList;

        List<ArticleEntity> stored = DatabaseManager.getInstance().getArticleDao().findArticleReadedByIdsLocal(ids);

        if (stored != null) {
            for (Article article : articleList) {
                for (ArticleEntity a : stored) {
                    if (article.getId().equals(a.getId())) {
                        article.setReadStatus(Article.STATUS_USER_HAS_READED);
                    }
                }
            }
        }

        return articleList;
    }

    /**
     * 记录已读过的文章
     *
     * @param article
     */
    public void addReadedArticle(Article article) {
        if (article.getReadStatus() == Article.STATUS_USER_HAS_READED)
            return;

        article.setReadStatus(Article.STATUS_USER_HAS_READED);

        ArticleEntity a = new ArticleEntity();

        a.setId(article.getId());
        a.setTitle(article.getTitle());
        a.setBaseUrl(article.getBase_url());
        a.setAuthor(article.getAuthor());
        a.setAuthorId(article.getAuthor_id());
        a.setReadum(article.getReadNum());
        a.setReadStatus(ArticleEntity.STATUS_USER_HAS_READED);

        //save 2 local db.
        DatabaseManager.getInstance().getArticleDao().insertOrReplace(a);
    }

    /**
     * 将文章item标记为已读
     *
     * @param view
     * @param article
     */
    public void tagAsReaded(View view, Article article) {
        TextView title = (TextView) view.findViewById(R.id.tv_title);
        if (title != null && article != null) {
            title.setTextColor(ContextCompat.getColor(mContext, R.color.listItem_desc_color));
            addReadedArticle(article);
        }
    }

    /**
     * 返回当前item的样式
     */
    public int getItemViewType(int position) {
        Article article = getItem(position);
        return article.getShowStyle();
    }

    /**
     * 返回view样式种类总数
     */
    public int getViewTypeCount() {
        return 3;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Article article = getItem(position);
        int type = getItemViewType(position);
        TextDataHolder textDataHolder;
        CommonDataHolder commonDataHolder;
        PicOnlyDataHolder picOnlyDataHolder;
        if (null == convertView || null == convertView.getTag()) {
            switch (type) {
                case Article.SHOWSTYLE_TITLE:
                    convertView = layoutInflater.inflate(R.layout.articlelist_item_title_only, null);
                    textDataHolder = new TextDataHolder(convertView);
                    convertView.setTag(textDataHolder);
                    initTitleOnlyData(article, textDataHolder);
                    break;
                case Article.SHOWSTYLE_TITLE_IMG:
                    convertView = layoutInflater.inflate(R.layout.articlelist_item, null);
                    commonDataHolder = new CommonDataHolder(convertView);
                    convertView.setTag(commonDataHolder);
                    initCommonData(article, commonDataHolder);
                    break;
                case Article.SHOWSTYLE_IMG:
                    convertView = layoutInflater.inflate(R.layout.articlelist_item_pic_only, null);
                    picOnlyDataHolder = new PicOnlyDataHolder(convertView);
                    convertView.setTag(picOnlyDataHolder);
                    initPicOnlyData(article, picOnlyDataHolder, position);
                    break;
            }
        } else switch (type) {
            case Article.SHOWSTYLE_TITLE:
                textDataHolder = (TextDataHolder) convertView.getTag();
                initTitleOnlyData(article, textDataHolder);
                break;
            case Article.SHOWSTYLE_TITLE_IMG:
                commonDataHolder = (CommonDataHolder) convertView.getTag();
                initCommonData(article, commonDataHolder);
                break;
            case Article.SHOWSTYLE_IMG:
                picOnlyDataHolder = (PicOnlyDataHolder) convertView.getTag();
                initPicOnlyData(article, picOnlyDataHolder, position);
                break;
        }
        return convertView;
    }

    class TextDataHolder {
        MatchTextView tvTitle;
        TextView tvDesc;
        TextView tvFlag;
        TextView tvReadNum;
        TextView tvTime;
        LinearLayout llFlag;

        public TextDataHolder(View parent) {
            initView(parent);
        }

        private void initView(View parent) {
            tvTitle = (MatchTextView) parent.findViewById(R.id.tv_title);
            tvDesc = (TextView) parent.findViewById(R.id.tv_desc);
            tvFlag = (TextView) parent.findViewById(R.id.tv_flag);
            tvReadNum = (TextView) parent.findViewById(R.id.tv_read);
            tvTime = (TextView) parent.findViewById(R.id.tv_time);
            llFlag = (LinearLayout) parent.findViewById(R.id.ll_flag);
        }
    }

    class CommonDataHolder extends TextDataHolder {
        ImageView imageViewRight;

        public CommonDataHolder(View parent) {
            super(parent);
            initView(parent);
        }

        private void initView(View parent) {
            imageViewRight = (ImageView) parent.findViewById(R.id.img_cover);
        }
    }

    class PicOnlyDataHolder extends CommonDataHolder {
        ImageView imageViewLeft;
        ImageView imageViewMiddle;

        public PicOnlyDataHolder(View parent) {
            super(parent);
            initView(parent);
        }

        private void initView(View parent) {
            imageViewLeft = (ImageView) parent.findViewById(R.id.small_cover_left);
            imageViewMiddle = (ImageView) parent.findViewById(R.id.small_cover_middle);

            /* 设置多图时每张图片的宽高 */
            int width = (AndroidUtils.getWindowWidth(mContext) - 4 * mContext.getResources().getDimensionPixelSize(R.dimen.dp_10)) / 3;
            int height = 11 * width / 15;
            ViewUtils.setSize(imageViewLeft, width, height);
            ViewUtils.setSize(imageViewMiddle, width, height);
            ViewUtils.setSize(imageViewRight, width, height);
        }
    }

    /**
     * 加载多图item
     *
     * @param holder
     */
    private void initPicOnlyData(Article article, PicOnlyDataHolder holder, int position) {
        initDataWorld(article, holder);
        ImageView[] images = new ImageView[]{holder.imageViewLeft, holder.imageViewMiddle, holder.imageViewRight};
        String[] pic_urls = new String[images.length];
        initDataImage(pic_urls, images, article);
    }

    /**
     * 加载纯文字item
     *
     * @param holder
     */
    private void initTitleOnlyData(Article article, TextDataHolder holder) {
        initDataWorld(article, holder);
    }

    /**
     * 加载单图item
     *
     * @param holder
     */
    private void initCommonData(Article article, CommonDataHolder holder) {
        initDataWorld(article, holder);
        ImageView[] images = new ImageView[]{holder.imageViewRight};
        String[] pic_urls = new String[images.length];
        initDataImage(pic_urls, images, article);
        adjustmentHolder(holder);
    }

    /**
     * 填充文字
     *
     * @param holder
     */
    private void initDataWorld(Article article, TextDataHolder holder) {
        holder.tvTitle.setText(article.getTitle(), matchText);
        resetHolder(holder);

        //根据已读状态显示不同的标题颜色
        if (article.getReadStatus() == Article.STATUS_USER_HAS_READED) {
            holder.tvTitle.setTextColor(ContextCompat.getColor(mContext, R.color.listItem_flag_color));
        }

//        if (null == category) {
        category = article.getCategory();
//        }

        if (null != category.getOptional()) {
            for (int i = 0; i < category.getOptional().length; i++) {

                if (category.getOptional()[i] == Category.optionFlag) {
                    if (null != article.getArticle_tag() && article.getArticle_tag().size() > 0) {
                        holder.tvFlag.setText(article.getArticle_tag().get(0).getName());
                        holder.tvFlag.setVisibility(View.VISIBLE);
                    }
                }
                if (category.getOptional()[i] == Category.optionRead && article.getReadNum() != 0) {
                    holder.tvReadNum.setText(article.getReadNum() + "阅读");
                    holder.tvReadNum.setVisibility(View.VISIBLE);
                }
                if (category.getOptional()[i] == Category.optionTime) {
                    holder.tvTime.setText(DateUtils.dealWithDateInArticle(mContext, article.getPublishAt()));
                    holder.tvTime.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /* 统一控件数据复原 */
    private void resetHolder(TextDataHolder holder) {
        holder.tvFlag.setText("");
        holder.tvReadNum.setText("");
        holder.tvTime.setText("");
        holder.tvFlag.setVisibility(View.GONE);
        holder.tvReadNum.setVisibility(View.GONE);
        holder.tvTime.setVisibility(View.GONE);

        if (null != holder.tvDesc)
            holder.tvDesc.setText("");

        holder.tvTitle.setTextColor(ContextCompat.getColor(mContext, R.color.text_black));
    }

    /* 调整标签栏的布局位置 */
    private void adjustmentHolder(CommonDataHolder holder) {
        if (TextUtils.isEmpty(holder.tvDesc.getText().toString())) { // 没有描述的情况
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.img_cover);
            holder.llFlag.setLayoutParams(layoutParams);

        } else {
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.BELOW, R.id.tv_desc);
            layoutParams.setMargins(0, mContext.getResources().getDimensionPixelSize(R.dimen.dp_5), 0, 0);
            holder.llFlag.setLayoutParams(layoutParams);
        }
    }

    /**
     * 填充图片数据
     *
     * @param pic_urls
     * @param images
     */
    private void initDataImage(String[] pic_urls, ImageView[] images, Article article) {
        Attachment attachment = null;
        if (article.getAttachments() != null && article.getAttachments().size() > 0) {

            for (int i = 0, j = 0; i < article.getAttachments().size() && j < pic_urls.length; i++) {
                attachment = article.getAttachments().get(i);
                if (attachment.getUsage().equals(Constants.COVER)) {
                    pic_urls[j] = attachment.getBase_url() + "172x132";//attachment.getMiddle();
                    j++;
                }
            }
        }
        for (int i = 0; i < images.length; i++) {
            if (TextUtils.isEmpty(pic_urls[i])) {
                images[i].setVisibility(View.INVISIBLE);
            } else {
                images[i].setVisibility(View.VISIBLE);
                images[i].setImageURI(Uri.parse(pic_urls[i]));
            }
        }
    }
}
